﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace pLib
{
    /// <summary>
    /// XML TO Object
    /// XML TO Dictionary
    /// </summary>
    public class XMLToObject
    {
        //        doc.LoadXml(@"<xml>
        //<mengde>100</mengde>
        //<type>2</type>
        //<foo>bar</foo>
        //</xml>");
        /// <summary>
        /// map xml to Dictionary
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public Dictionary<string, string> XMLMapDictionary(string xml)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            Dictionary<string, string> d = new Dictionary<string, string>();
            foreach (XmlNode n in doc.SelectNodes("/xml/*"))
            {
                d[n.Name] = n.InnerText;
            }
            return d;
        }

        /*
         * <database>
         *      <def number="1" name="one"/>
         *      <def number="2" name="two"/>
         *  </database>
         */
        /// <summary>
        /// 
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public Dictionary<string, string> XMLMapDictionaryAttribute(string xml)
        {
            var data = XElement.Parse(xml)
                .Elements("def")
                .ToDictionary(
                    el => (string)el.Attribute("number"),
                    el => (string)el.Attribute("name")
                );
            return data;
        }

        /*
         * string s = "<data><resource key=\"123\">foo</resource><resource key=\"456\">bar</resource><resource key=\"789\">bar</resource></data>";
         */
        /// <summary>
        /// 
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public SortedDictionary<string, string> XMLMapDictionaryWithValueAttribute(string xml)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(xml);
            XmlNodeList resources = xmlDocument.SelectNodes("data/resource");
            SortedDictionary<string, string> dictionary = new SortedDictionary<string, string>();
            foreach (XmlNode node in resources)
            {
                dictionary.Add(node.Attributes["key"].Value, node.InnerText);
            }
            return dictionary;
        }
    }
}
